<template>
  <div class="dialog">
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="25%"
      :before-close="handleClose"
      :modal="false"
      draggable
    >
      <div class="dialog-line"></div>
      <div class="dialog-con">
        <!-- 新增用户 -->
        <el-form
          size="small"
          ref="formRef"
          :inline="true"
          :model="dialogRelevant.formAdd"
          :rules="dialogRelevant.rules"
          label-width="90px"
        >
          <el-form-item label="设备序列号" class="filter" prop="serial_no">
            <el-input
              v-model.trim="dialogRelevant.formAdd.serial_no"
              placeholder="请输入"
              maxLength="40"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="设备名称" class="filter" prop="name">
            <el-input
              v-model.trim="dialogRelevant.formAdd.name"
              placeholder="请输入"
              maxLength="40"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="设备品牌" class="filter" prop="brand">
            <el-select v-model="dialogRelevant.formAdd.brand" @change="dialogRelevant.changeBrand($event)" clearable>
              <el-option v-for="(item, index) in brandList" :key="index" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="设备型号" class="filter" prop="model_id">
            <el-select v-model="dialogRelevant.formAdd.model_id" :disabled="!dialogRelevant.formAdd.brand" clearable>
              <el-option v-for="item in modelList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="所属单位" class="filter" prop="unit_id" v-if="userInfo.role_name === '超级管理员'">
            <el-select
              v-model="dialogRelevant.formAdd.unit_id"
              filterable
              remote
              :remote-method="remoteMethod"
              clearable
            >
              <el-option
                v-for="item in dialogRelevant.companyList"
                :key="item.id"
                :label="item.unit_name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="联系人" class="filter" prop="contact_user">
            <el-input
              v-model.trim="dialogRelevant.formAdd.contact_user"
              placeholder="请输入"
              maxLength="40"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="联系人电话" class="filter" prop="contact_mobile">
            <el-input
              v-model.trim="dialogRelevant.formAdd.contact_mobile"
              placeholder="请输入"
              maxLength="40"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="设备状态" class="filter" prop="status">
            <el-select v-model="dialogRelevant.formAdd.status" clearable>
              <el-option v-for="item in stateList" :key="item.id" :label="item.key" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间" class="filter" v-if="dialogTitle === '编辑'">
            <el-input
              v-model.trim="dialogRelevant.formAdd.password"
              placeholder="请输入"
              maxLength="40"
              :disabled="dialogTitle === '编辑'"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="登记位置" class="filter">
            <div class="dialog-lnglat">
              <el-input
                v-model.trim="dialogRelevant.formAdd.longitude"
                placeholder="请输入经度"
                maxLength="40"
                clearable
              ></el-input>
              <el-input
                v-model.trim="dialogRelevant.formAdd.latitude"
                placeholder="请输入纬度"
                maxLength="40"
                clearable
                style="margin-right: 20px"
              ></el-input>
            </div>
          </el-form-item>
          <div class="dialog-location" @click="dialogRelevant.clickLocation">
            <img src="@/assets/img/device/icon_location.png" alt="" />
            <span style="padding: 0 10px; cursor: pointer">定位</span>
          </div>
        </el-form>
      </div>
      <div class="dialog-line"></div>
      <template #footer>
        <span class="dialog-footer">
          <el-button class="btn-cancel" @click="dialogRelevant.dialogCancel">取消</el-button>
          <el-button class="btn-confirm" type="primary" @click="dialogRelevant.dialogConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 地图 -->
    <comMapPoint
      v-if="mapVisible"
      :mapVisible="mapVisible"
      @closeDialog="closeMapDialog"
      @updateLocation="updateLocation"
    ></comMapPoint>
  </div>
</template>
<script lang="ts" setup>
import {ref, reactive, onMounted, defineProps, defineEmits} from 'vue';
import {ElMessage} from 'element-plus';
import comMapPoint from '@/components/comMapPoint/index.vue';
import registerApi from '@/api/register.ts';
import manageApi from '@/api/manage.ts';
import {validateAccount} from '@/utils/validator.js';

const dialogVisible = ref(true);
const dialogTitle = ref('');
const mapVisible = ref(false);
const modelList = ref([]); // 设备型号
const stateList = ref([]); // 设备状态
const brandList = ref([]); // 设备品牌
const userInfo = JSON.parse(localStorage.getItem('userInfo')) || '';

const props = defineProps({
  dialogVisible: Boolean,
  dialogTitle: String,
  serialNo: String,
  id: Number,
});

const emit = defineEmits(['closeDialog', 'updateList']);

const handleClose = () => {
  emit('closeDialog');
};

// 弹窗相关
const formRef = ref(null);
const dialogRelevant = reactive({
  formAdd: {
    serial_no: '',
    model_id: '',
    name: '',
    unit_id: '',
    contact_user: '',
    contact_mobile: '',
    status: '',
    latitude: '',
    longitude: '',
  },
  rules: {
    serial_no: [{required: true, message: '请输入设备序列号', trigger: 'blur'}],
    name: [{required: true, message: '请输入设备名称', trigger: 'blur'}],
    brand: [{required: true, message: '请选择设备品牌', trigger: 'change'}],
    model_id: [{required: true, message: '请选择设备型号', trigger: 'change'}],
    unit_id: [{required: true, message: '请选择所属单位', trigger: 'change'}],
    contact_user: [{required: true, message: '请输入联系人', trigger: 'blur'}],
    contact_mobile: [{validator: validateAccount, trigger: 'blur'}],
    status: [{required: true, message: '请选择设备状态', trigger: 'change'}],
  },
  companyList: [],
  // 选择设备品牌
  changeBrand: (val) => {
    getModelList(val);
    dialogRelevant.formAdd.model_id = '';
  },
  // 定位
  clickLocation: () => {
    mapVisible.value = !mapVisible.value;
  },
  dialogCancel: () => {
    dialogRelevant.formAdd = {
      serial_no: '',
      model_id: '',
      name: '',
      unit_id: '',
      contact_user: '',
      contact_mobile: '',
      status: '',
      latitude: '',
      longitude: '',
    };
    formRef.value.clearValidate();
    handleClose();
  },
  dialogConfirm: () => {
    if (props.dialogTitle === '新增设备') {
      addFnc();
    } else {
      editFnc();
    }
  },
});

// 新增
const addFnc = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (!dialogRelevant.formAdd.latitude && !dialogRelevant.formAdd.longitude) {
        ElMessage.error('请输入登记位置');
        return;
      }
      if (userInfo.role_name !== '超级管理员') {
        dialogRelevant.formAdd.unit_id = userInfo.unit_id;
      }
      manageApi
        .deviceManageSave(dialogRelevant.formAdd)
        .then((res) => {
          if (res.status === 0) {
            ElMessage.success(res.message);
            handleClose();
            emit('updateList');
            dialogRelevant.formAdd = {
              serial_no: '',
              model_id: '',
              name: '',
              unit_id: '',
              contact_user: '',
              contact_mobile: '',
              status: '',
              latitude: '',
              longitude: '',
            };
          }
        })
        .catch((err) => {
          throw err;
        });
    }
  });
};
// 编辑
const editFnc = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (!dialogRelevant.formAdd.latitude && !dialogRelevant.formAdd.longitude) {
        ElMessage.error('请输入登记位置');
        return;
      }
      if (userInfo.role_name !== '超级管理员') {
        dialogRelevant.formAdd.unit_id = userInfo.unit_id;
      }
      const params = {
        serial_no: dialogRelevant.formAdd.serial_no,
        model_id: dialogRelevant.formAdd.model_id,
        name: dialogRelevant.formAdd.name,
        unit_id: dialogRelevant.formAdd.unit_id,
        contact_user: dialogRelevant.formAdd.contact_user,
        contact_mobile: dialogRelevant.formAdd.contact_mobile,
        status: dialogRelevant.formAdd.status,
        latitude: dialogRelevant.formAdd.latitude,
        longitude: dialogRelevant.formAdd.longitude,
        id: props.id,
      };
      manageApi
        .deviceManageSave(params)
        .then((res) => {
          if (res.status === 0) {
            ElMessage.success(res.message);
            handleClose();
            emit('updateList');
          }
        })
        .catch((err) => {
          throw err;
        });
    }
  });
};

// 子组件方法
const closeMapDialog = () => {
  mapVisible.value = !mapVisible.value;
};
const updateLocation = (lnglat) => {
  dialogRelevant.formAdd.longitude = lnglat[0].toString();
  dialogRelevant.formAdd.latitude = lnglat[1].toString();
};

// 获取单位列表
const getCompanyList = () => {
  registerApi
    .getCompanyList()
    .then((res) => {
      dialogRelevant.companyList = res.data;
    })
    .catch((err) => {
      throw err;
    });
};
// 搜索单位列表
const remoteMethod = (query: string) => {
  if (query) {
    registerApi
      .getCompanyList({keyword: query})
      .then((res) => {
        dialogRelevant.companyList = res.data;
      })
      .catch((err) => {
        throw err;
      });
  } else {
    dialogRelevant.companyList = [];
  }
};
// 获取设备型号列表
const getModelList = (brand) => {
  manageApi
    .deviceModelList({brand_id: brand})
    .then((res) => {
      modelList.value = res.data;
    })
    .catch((err) => {
      throw err;
    });
};
// 获取设备型号列表
const getBrandList = () => {
  manageApi
    .deviceBrandList()
    .then((res) => {
      brandList.value = res.data;
    })
    .catch((err) => {
      throw err;
    });
};
// 获取设备状态列表
const getStateList = () => {
  manageApi
    .deviceStateList()
    .then((res) => {
      stateList.value = res.data;
    })
    .catch((err) => {
      throw err;
    });
};
// 获取详情数据
const getDetailData = () => {
  manageApi
    .deviceManageDetails({serial_no: props.serialNo})
    .then((res) => {
      dialogRelevant.formAdd = {
        serial_no: res.data.serial_no,
        model_id: res.data.model_id,
        name: res.data.name,
        brand: res.data.brand_name,
        unit_id: res.data.unit_id,
        contact_user: res.data.contact_user,
        contact_mobile: res.data.contact_mobile,
        status: res.data.status,
        latitude: res.data.latitude,
        longitude: res.data.longitude,
      };
    })
    .catch((err) => {
      throw err;
    });
};

onMounted(() => {
  getCompanyList();
  getModelList();
  getBrandList();
  getStateList();
  dialogTitle.value = props.dialogTitle;
  if (props.dialogTitle === '编辑') {
    getDetailData();
  }
});
</script>
<style lang="scss" scoped>
.dialog {
  &:deep(.el-dialog__body) {
    padding: 0;
  }
  &:deep(.el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:before) {
    content: '' !important;
  }
  .dialog-con {
    .el-form {
      display: flex;
      flex-direction: column;
      padding: 24px 48px;
      padding-top: 12px;
    }
    .el-form-item {
      margin-top: 15px;
      .el-input {
        width: 280px;
      }
      .el-select {
        width: 280px;
        &:deep(.el-input--suffix) {
          width: 280px;
        }
      }
    }

    &:deep(.el-form-item__label) {
      margin-right: 34px;
      text-align: right !important;
    }
    .dialog-lnglat {
      display: flex;
      justify-content: space-between;
      .el-input {
        width: 130px;
        margin-right: 20px;
      }
    }
    .dialog-location {
      display: flex;
      align-items: center;
      width: 130px;
      height: 32px;
      background: rgba(212, 212, 212, 0.3);
      border-radius: 2px;
      border: 1px solid #d4d4d4;
      margin: 15px 0 0 1.4rem;
      box-sizing: border-box;
      padding-left: 15px;
    }
  }
  .dialog-line {
    height: 1px;
    background: rgba(0, 0, 0, 0.06);
  }
}
@media only screen and (max-width: 1366px) and (min-width: 768px) {
  .dialog {
    &:deep(.el-dialog) {
      width: 35% !important;
    }
  }
}
</style>
